import { defineStore } from 'pinia';
import { readonly, ref } from 'vue';

export interface UserInfo {
  username: string;
  nickname: string;
  avatar: string;
  roles: string[];
  permissions: string[];
}

export interface LoginState {
  token: string;
  refreshToken: string;
  userInfo: UserInfo;
}

export const useLoginStore = defineStore(
  'login',
  () => {
    // 状态
    const token = ref<string>('');
    const refreshToken = ref<string>('');
    const userInfo = ref<UserInfo | null>(null);
    const isLoggedIn = ref<boolean>(false);

    // 获取器
    const getToken = () => token.value;
    const getRefreshToken = () => refreshToken.value;
    const getUserInfo = () => userInfo.value;
    const getIsLoggedIn = () => isLoggedIn.value;

    // 操作
    const login = async (loginData: LoginState) => {
      token.value = loginData.token;
      refreshToken.value = loginData.refreshToken;
      userInfo.value = loginData.userInfo;
      isLoggedIn.value = true;

      // 使用pinia持久化机制，不再直接操作localStorage
      // 数据将通过pinia的persist插件自动保存到"pinia-login"键
    };

    const logout = async () => {
      token.value = '';
      refreshToken.value = '';
      userInfo.value = null;
      isLoggedIn.value = false;

      // 清除cookie和localStorage（微前端跨端口共享）
      try {
        const { clearTokens } = await import('@tuxing/core-token');
        clearTokens();
        console.log('[LoginStore] All tokens cleared on logout');
      } catch (error) {
        console.error('[LoginStore] Failed to clear tokens:', error);
      }

      // 跳转到登录页面，使用与登录成功相同的跳转逻辑
      const mainAppUrl =
        import.meta.env.VITE_MAIN_APP_URL || (import.meta.env.DEV ? 'http://localhost:3001' : window.location.origin);
      const loginUrl = `${mainAppUrl}/login`;

      console.log('[LoginStore] Logout redirect to:', loginUrl);
      console.log('[LoginStore] Current env:', {
        VITE_MAIN_APP_URL: import.meta.env.VITE_MAIN_APP_URL,
        DEV: import.meta.env.DEV,
        location: window.location.href,
      });

      window.location.href = loginUrl;
    };

    const updateToken = (newToken: string) => {
      token.value = newToken;
      // 使用pinia持久化机制，不再直接操作localStorage
    };

    const updateUserInfo = (newUserInfo: UserInfo) => {
      userInfo.value = newUserInfo;
      // 使用pinia持久化机制，不再直接操作localStorage
    };

    // 从 localStorage 恢复状态
    const restoreState = () => {
      // 不再从localStorage直接恢复，使用pinia的persist插件自动恢复
      // 检查pinia-login存储中是否有数据
      const piniaLoginData = localStorage.getItem('pinia-login');
      if (piniaLoginData) {
        try {
          const data = JSON.parse(piniaLoginData);
          if (data.state) {
            token.value = data.state.token || '';
            refreshToken.value = data.state.refreshToken || '';
            userInfo.value = data.state.userInfo || null;
            isLoggedIn.value = !!data.state.token;
          }
        } catch (e) {
          console.error('Failed to parse pinia-login data:', e);
        }
      }
    };

    // 检查 token 是否有效
    const isTokenValid = (): boolean => {
      if (!token.value) return false;

      try {
        // 简单的 JWT token 检查（实际应该验证过期时间）
        const payload = JSON.parse(atob(token.value.split('.')[1]));
        const currentTime = Date.now() / 1000;
        return payload.exp > currentTime;
      } catch {
        return false;
      }
    };

    return {
      // 状态
      token: readonly(token),
      refreshToken: readonly(refreshToken),
      userInfo: readonly(userInfo),
      isLoggedIn: readonly(isLoggedIn),

      // 获取器
      getToken,
      getRefreshToken,
      getUserInfo,
      getIsLoggedIn,

      // 操作
      login,
      logout,
      updateToken,
      updateUserInfo,
      restoreState,
      isTokenValid,
    };
  },
  {
    persist: {
      storage: localStorage,
      key: 'pinia-login',
      paths: ['token', 'refreshToken', 'userInfo', 'isLoggedIn'],
      afterRestore: (ctx) => {
        console.log('[LoginStore] After restore - current token:', ctx.store.token);
      },
    },
  },
);
